package com.javaforever.gatescore.gui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.javaforever.gatescore.core.FrontProject;
import org.javaforever.gatescore.poi.SpreadSheetTranslater;


@SuppressWarnings("serial")
public class ParseExcelGui extends JFrame implements MouseListener, ActionListener {
	public static void main(String [] args) {
		ParseExcelGui runnerui = new ParseExcelGui();
		runnerui.setVisible(true);
	}
	
	private AboutFrame about;

	private JMenuBar mb;
	
	private JMenu mRun;
	
	private JMenu mDown;

	private JMenu mHelp;

	private JMenuItem miAbout;

	private JMenuItem miHelp;
	
	private JMenuItem miSwitch;

	private JMenuItem miRun;
	
	private JMenuItem miExit;
	
	private JMenuItem miReadme;
	
	private JMenuItem miInstall;
	
	private JMenuItem miUserManual;
	
	private JMenuItem miTheory1;
	
	private JMenuItem miTheory2;
	
	private JMenuItem miTheory3;
	
	private JMenuItem miTheory4;
	
	private JMenuItem miTheory5;
	
	private JMenuItem miGift;
	
	private JMenuItem miCompleteSample;
	
	private JMenuItem miCompleteOracleEn;
	
	private JMenuItem miCompleteOracleAdvancedEn;
	
	private JMenuItem miGenerateSample;

	private JMenuItem miAdvanced;
	
	private JMenuItem miGenerateOracle;
	
	private JMenuItem miGenerateOracleEn;
	
	private JMenuItem miGenerateOracleAdvanced;
	
	private JMenuItem miGenerateOracleAdvancedEn;
	
	private JMenuItem miDualLangBBS;
	
	private JMenuItem miDualLangBBSOracle;

	private JMenuItem miOne;

	private JMenuItem miEmployeeTest;

	private JMenuItem miUserSystem;

	private JMenuItem miFields;

	private JMenuItem miSports;

	private JMenuItem miProject;
	
	private JPanel pane;
	
	private GridBagLayout gridbag;
	
	private GridBagConstraints constraints;
	
	private GridBagConstraints constraints3;
	
	private JLabel lblExcelSheet;
	
	private JTextField txtExcelSheet;
	
	private JButton btnUpload;
	
	private JCheckBox chkProjectName;
	
	private JButton btnRun;
	
	public static  AppStarter appStarter;

	// Constructor of the game
	public ParseExcelGui() {
		super("时空之门前端代码生成器");
		try {
			String windows="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
			UIManager.setLookAndFeel(windows);
			 
			setSize(600, 1200);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
			
			gridbag = new GridBagLayout();
			constraints = new GridBagConstraints();
			//constraints.fill = GridBagConstraints.BOTH;
			constraints.anchor = GridBagConstraints.CENTER;
			constraints.ipady = 10;
			constraints.insets = new Insets(0,0,10,10);
			constraints.gridheight = 7;
			constraints.gridwidth = 0;			

			pane = new JPanel();	
			
			lblExcelSheet = new JLabel("Excel模板:");
			lblExcelSheet.setSize(300,120);
			
			txtExcelSheet = new JTextField("                         ");
			txtExcelSheet.setSize(500, 120);
			txtExcelSheet.addActionListener(this);
			
			btnUpload = new JButton("上传Excel模板 ");
			btnUpload.setSize(300, 100);
			btnUpload.addActionListener(this);
			
			chkProjectName = new JCheckBox("API使用项目名",false);
			chkProjectName.addActionListener(this);
			
			btnRun = new JButton("代码生成");
			btnRun.setSize(300, 100);
			btnRun.addActionListener(this);
			
			gridbag.setConstraints(lblExcelSheet, constraints);
			gridbag.setConstraints(txtExcelSheet, constraints);
			gridbag.setConstraints(btnUpload, constraints);
			gridbag.setConstraints(chkProjectName, constraints);
			gridbag.setConstraints(btnRun, constraints);
			
			pane.setLayout(gridbag);
			
			pane.add(lblExcelSheet);
			pane.add(txtExcelSheet);
			pane.add(btnUpload);
			pane.add(chkProjectName);
			pane.add(btnRun);
			
			// Begin Menu Set
			mb = new JMenuBar();
			mRun = new JMenu("功能");
			miSwitch = new JMenuItem("切换SGS代码生成");
			miSwitch.addActionListener(this);
			miRun = new JMenuItem("代码生成");
			miRun.addActionListener(this);
			
			miExit = new JMenuItem("退出");
			miExit.addActionListener(this);

			mb.add(mRun);
			mRun.add(miSwitch);
			mRun.add(miRun);

			mRun.addSeparator();
			mRun.add(miExit);
			
			
			mDown = new JMenu("下载示例");
			miCompleteSample = new JMenuItem("CompleteSample示例");
			miCompleteSample.addActionListener(this);
			miCompleteOracleEn = new JMenuItem("CompleteOracleEn示例");
			miCompleteOracleEn.addActionListener(this);
			miCompleteOracleAdvancedEn = new JMenuItem("CompleteOracleAdvancedEn示例");
			miCompleteOracleAdvancedEn.addActionListener(this);
			miGenerateSample = new JMenuItem("GenerateSample示例");
			miGenerateSample.addActionListener(this);
			miAdvanced= new JMenuItem("先进特性示例");
			miAdvanced.addActionListener(this);
			miGenerateOracle = new JMenuItem("GenerateOracle示例");
			miGenerateOracle.addActionListener(this);
			miGenerateOracleEn = new JMenuItem("GenerateOracleEn示例");
			miGenerateOracleEn.addActionListener(this);
			miGenerateOracleAdvanced = new JMenuItem("GenerateOracleAdvanced示例");
			miGenerateOracleAdvanced.addActionListener(this);
			miGenerateOracleAdvancedEn = new JMenuItem("GenerateOracleAdvancedEn示例");
			miGenerateOracleAdvancedEn.addActionListener(this);
			miDualLangBBS = new JMenuItem("DualLangBBS示例");
			miDualLangBBSOracle = new JMenuItem("DualLangBBSOracle示例");
			miDualLangBBS.addActionListener(this);
			miOne = new JMenuItem("One示例");
			miOne.addActionListener(this);
			miEmployeeTest = new JMenuItem("EmployeeTest示例");
			miEmployeeTest.addActionListener(this);
			miUserSystem = new JMenuItem("用户系统示例");
			miUserSystem.addActionListener(this);
			miFields= new JMenuItem("场馆管理系统示例");
			miFields.addActionListener(this);
			miSports= new JMenuItem("运动示例");
			miSports.addActionListener(this);
			miProject = new JMenuItem("项目管理示例");
			miProject.addActionListener(this);
			mDown.add(miCompleteSample);
			mDown.add(miCompleteOracleEn);
			mDown.add(miCompleteOracleAdvancedEn);
			mDown.add(miGenerateSample);
			mDown.add(miAdvanced);
			mDown.add(miGenerateOracle);
			mDown.add(miGenerateOracleEn);
			mDown.add(miGenerateOracleAdvanced);
			mDown.add(miGenerateOracleAdvancedEn);
			mDown.add(miDualLangBBS);
			mDown.add(miDualLangBBSOracle);
			mDown.add(miOne);
			mDown.add(miEmployeeTest);
			mDown.add(miUserSystem);
			mDown.add(miFields);
			mDown.add(miSports);
			mDown.add(miProject);

			mb.add(mDown);
	
			mHelp = new JMenu("帮助");
			miReadme = new JMenuItem("阅读说明");
			miReadme.addActionListener(this);
			miInstall = new JMenuItem("下载运行文档");
			miInstall.addActionListener(this);
			miUserManual = new JMenuItem("下载用户手册");
			miUserManual.addActionListener(this);
			miTheory1 = new JMenuItem("下载理论文档一");
			miTheory1.addActionListener(this);
			miTheory2 = new JMenuItem("下载理论文档二");
			miTheory2.addActionListener(this);
			miTheory3 = new JMenuItem("下载理论文档三");
			miTheory3.addActionListener(this);
			miTheory4 = new JMenuItem("下载理论文档四");
			miTheory4.addActionListener(this);
			miTheory5 = new JMenuItem("下载理论文档五");
			miTheory5.addActionListener(this);
			miGift = new JMenuItem("下载神秘礼物");
			miGift.addActionListener(this);
			miAbout = new JMenuItem("关于...");
			miAbout.addActionListener(this);
			//mHelp.add(miReadme);
			mHelp.add(miInstall);
			mHelp.add(miUserManual);
			mHelp.add(miTheory1);
			mHelp.add(miTheory2);
			mHelp.add(miTheory3);
			mHelp.add(miTheory4);
			mHelp.add(miTheory5);
			mHelp.add(miGift);
		
			miAbout = new JMenuItem("关于...");
			mHelp.add(miAbout);
			miAbout.addActionListener(this);
			mb.add(mHelp);
			this.setJMenuBar(mb);
			// end of Menu Set
	
			setContentPane(pane);
			setSize(600, 1200);
			setLocationRelativeTo(null);//窗口在屏幕中间显示
			setVisible(false);

			// About Frame
			about = new AboutFrame("关于时空之门前端代码生成器");
		} catch (Exception e){
			e.printStackTrace();
		}
	}

	public void actionPerformed(ActionEvent e) {
		try {
			if (e.getSource() == miAbout) {
				about.setVisible(true);
			}
			
			if (e.getSource() == miRun) {
				JOptionPane.showMessageDialog(null, "测试已运行结束，请检查运行文件夹中的结果Excel文件！", "运行结束", JOptionPane.PLAIN_MESSAGE);
			}
			
			if (e.getSource() == miSwitch) {
				AppStarter.switchToSGS();
			}
			
			if (e.getSource() == miCompleteSample){
				downloadRes("/spreadsheettemplates/CompleteSample.xls","CompleteSample.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miCompleteOracleEn){
				downloadRes("/spreadsheettemplates/CompleteOracleEn.xls","CompleteOracleEn.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miCompleteOracleAdvancedEn){
				downloadRes("/spreadsheettemplates/CompleteOracleAdvancedEn.xls","CompleteOracleAdvancedEn.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miGenerateSample){
				downloadRes("/spreadsheettemplates/GenerateSample.xls","GenerateSample.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miAdvanced){
				downloadRes("/spreadsheettemplates/GenerateAdvanced.xls","GenerateAdvanced.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miGenerateOracle){
				downloadRes("/spreadsheettemplates/GenerateOracle.xls","GenerateOracle.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miGenerateOracleEn){
				downloadRes("/spreadsheettemplates/GenerateOracleEn.xls","GenerateOracleEn.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miGenerateOracleAdvanced){
				downloadRes("/spreadsheettemplates/GenerateOracleAdvanced.xls","GenerateOracleAdvanced.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miGenerateOracleAdvancedEn){
				downloadRes("/spreadsheettemplates/GenerateOracleAdvancedEn.xls","GenerateOracleAdvancedEn.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miDualLangBBS){
				downloadRes("/spreadsheettemplates/DualLangBBS.xls","DualLangBBS.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miDualLangBBSOracle){
				downloadRes("/spreadsheettemplates/DualLangBBSOracle.xls","DualLangBBSOracle.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miOne){
				downloadRes("/spreadsheettemplates/One.xls","One.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miEmployeeTest){
				downloadRes("/spreadsheettemplates/EmployeeTest.xls","EmployeeTest.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miUserSystem){
				downloadRes("/spreadsheettemplates/UserSystem.xls","UserSystem.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miFields){
				downloadRes("/spreadsheettemplates/MyAreas.xls","MyAreas.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miSports){
				downloadRes("/spreadsheettemplates/MySports.xls","MySports.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miProject){
				downloadRes("/spreadsheettemplates/MyProject.xls","MyProject.xls");  
				JOptionPane.showMessageDialog(null,  "恭喜，示例已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			
			if (e.getSource() == miInstall){
				downloadRes("/docs/GatesCore_Usage_3_0_0.docx","GatesCore_Usage_3_0_0.docx");  
				JOptionPane.showMessageDialog(null,  "恭喜，文档已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miUserManual){
				downloadRes("/docs/GatesCore_UserManual_3_0_0.docx","GatesCore_UserManual_3_0_0.docx");  
				JOptionPane.showMessageDialog(null,  "恭喜，文档已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			
			if (e.getSource() == miTheory1){
				downloadRes("/docs/超级语言.pptx","超级语言.pptx");  
				JOptionPane.showMessageDialog(null,  "恭喜，理论文档一已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miTheory2){
				downloadRes("/docs/代码生成原理浅析.ppt","代码生成原理浅析.ppt"); 
				JOptionPane.showMessageDialog(null,  "恭喜，理论文档二已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miTheory3){
				downloadRes("/docs/动词算子式通用目的代码生成器基础理论讲纲Update2.pptx","动词算子式通用目的代码生成器基础理论讲纲Update2.pptx");  
				JOptionPane.showMessageDialog(null,  "恭喜，理论文档三已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miTheory4){
				downloadRes("/docs/Infinity面向棱柱动词算子式通用目的代码生成器详细设计Update3.ppt","Infinity面向棱柱动词算子式通用目的代码生成器详细设计Update3.ppt");  
				JOptionPane.showMessageDialog(null,  "恭喜，理论文档四已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			if (e.getSource() == miTheory5){
				downloadRes("/docs/动词算子式代码生成器设计技术理论及实现.pptx","动词算子式代码生成器设计技术理论及实现.pptx");  
				JOptionPane.showMessageDialog(null,  "恭喜，理论文档五已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);}
			if (e.getSource() == miGift){
				String [] fileNames = {"clocksimplejee4_0_98.zip","TestDemo_allcorrect_20170410.zip"};
				String fileName = fileNames[(int)(Math.random()*2.0)];
				downloadRes("/docs/"+fileName,fileName); 
				JOptionPane.showMessageDialog(null,  "恭喜，神秘礼物已经下载成功！","下载成功", JOptionPane.INFORMATION_MESSAGE);
			}
			
			if (e.getSource() == btnRun) {
				File dir = new File(".");			
				String excelFolderPath = dir.getAbsolutePath().substring(0,dir.getAbsolutePath().length()-1);
				String excelFileName = txtExcelSheet.getText();
				String savePath = excelFolderPath;
				SpreadSheetTranslater translater = new SpreadSheetTranslater();
				InputStream is = new FileInputStream(excelFolderPath+excelFileName);
				POIFSFileSystem fs = new POIFSFileSystem(is);
				HSSFWorkbook wb = new HSSFWorkbook(fs);
				FrontProject project = translater.translate(wb);
				project.setShowBackendProject(chkProjectName.isSelected());
				project.setFolderPath(savePath);
				JarProjectExportUtil.generateProjectZip(project);	
				JOptionPane.showMessageDialog(null, "恭喜，代码生成已经成功！", "代码生成成功", JOptionPane.PLAIN_MESSAGE);
			}
			
			if (e.getSource() == btnUpload) {
				JFileChooser fd = new JFileChooser();
				fd.setDialogTitle("打开Excel模板");
				XlsFileFilter xfilter = new XlsFileFilter("xls");
				fd.addChoosableFileFilter(xfilter);
				fd.setFileFilter(xfilter);
				//fd.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
				int result = fd.showOpenDialog(this);
				if (result == JFileChooser.APPROVE_OPTION) {
					File f = fd.getSelectedFile();  
					if(f != null){
						String filename= f.getName();
						
						File dir = new File(".");
						String dirFolder = dir.getAbsolutePath().substring(0,dir.getAbsolutePath().length()-1);
						File destFolder = new File(dirFolder);
						File destFile =  new File(dirFolder + "/" + filename);
						File[] destFiles = destFolder.listFiles(xfilter);
						for (File df:destFiles) df.delete();
						
						copyFile(f,destFile);					
					
						txtExcelSheet.setText(filename);
						JOptionPane.showMessageDialog(null, "测试案例"+filename+"已上传，可以运行！", "上传成功", JOptionPane.PLAIN_MESSAGE);
					}  
				}
			}
			
		} catch (Exception ie) {
			ie.printStackTrace();;
		}
	}
	
	public void cleanWorkFolder(){
		File dir = new File(".");
		String dirFolder = dir.getAbsolutePath().substring(0,dir.getAbsolutePath().length()-1);
		File [] files = dir.listFiles();
		for (File f:files){
			String fname = f.getName();
			String [] fnames = fname.split(".");
			String fext = "";
			if (fnames.length >= 1)  fext = fnames[fnames.length-1];
			if (fext!=null && !fext.equals("") && fext.equals("xls")&&fname!=null&&!fname.endsWith("Result.xls")){
				f.delete();
			}		
		}
			
	}

	// the mouse events listener methods
	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
	protected void downloadRes(String filePath, String newFileName)throws Exception{
		new Resource().downloadRes(filePath,newFileName);
	}
	
	 // 复制文件
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
}

class XlsFileFilter extends FileFilter implements FilenameFilter {
	String ext;

	public XlsFileFilter(String ext) {
		this.ext = ext;
	}

	/* 在accept()方法中,当程序所抓到的是一个目录而不是文件时,我们返回true值,表示将此目录显示出来. */
	public boolean accept(File file) {
		if (file.isDirectory()) {
			return true;
		}
		String fileName = file.getName();
		int index = fileName.lastIndexOf('.');
		if (index > 0 && index < fileName.length() - 1) {
			// 表示文件名称不为".xxx"现"xxx."之类型
			String extension = fileName.substring(index + 1).toLowerCase();
			String firstFileName =  fileName.substring(0,index).toLowerCase();
			// 若所抓到的文件扩展名等于我们所设置要显示的扩展名(即变量ext值),则返回true,表示将此文件显示出来,否则返回
			// true.
			if (extension.equals(ext)&&!firstFileName.endsWith("result"))
				return true;
		}
		return false;
	}

	// 实现getDescription()方法,返回描述文件的说明字符串!!!
	public String getDescription() {
		if (ext.equals("xls"))
			return "Excel files(*.xls)";
		return "";
	}

	@Override
	public boolean accept(File dir, String name) {
		return this.accept(new File(dir.getAbsolutePath()+"/"+name));
	}
}




